package com.example.communist_app_api.service.impl;

import com.example.communist_app_api.db.dao.PermissionDao;
import com.example.communist_app_api.db.dto.PermissionDTO;
import com.example.communist_app_api.db.pojoDto.Action;
import com.example.communist_app_api.db.pojoDto.Module;
import com.example.communist_app_api.db.pojoDto.Permission;
import com.example.communist_app_api.service.ActionService;
import com.example.communist_app_api.service.ModuleService;
import com.example.communist_app_api.service.PermissionService;
import com.example.communist_app_api.service.RolePermissionService;
import com.example.communist_app_api.vo.web.req.MenuCreateReq;
import com.example.communist_app_api.vo.web.req.MenuDeleteMenuMessageReq;
import com.example.communist_app_api.vo.web.req.MenuUpdateMessageReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author love~mlm
 * @version 1.0
 * Create by 2022/11/19 18:38
 */
@Transactional
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private ModuleService moduleService;
    @Autowired
    private ActionService actionService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public Permission getPermissionByPermissionId(Integer permissionId) {
        return permissionDao.getPermissionByPermission(permissionId);
    }

    //对权限进行分级
    @Override
    public List<PermissionDTO> getPermissionMenuList(Integer roleId) {
        //找父节点
        //可能有多个父节点为0的节点，构成一个List集合
        List<Permission> permissionList = permissionDao.getAllPermission();

        List<PermissionDTO> permissionDTOList = new ArrayList<>();

        //返回权限菜单列表
        List<PermissionDTO> resultMenuList = new ArrayList<>();

        if (roleId != 0) {

        }
        //根据roleId获取角色已经拥有的权限,然后拥有的权限checked为true
        ArrayList<Integer> permissionIdByRoleId = rolePermissionService.getPermissionIdByRoleId(roleId);


        //循环遍历所有权限信息
        for (Permission permission : permissionList) {
            PermissionDTO permissionDTO = new PermissionDTO();
            //权限id
            permissionDTO.setId(permission.getId());
            //权限名称
            permissionDTO.setPermissionName(permission.getPermissionName());
            //权限父节点
            permissionDTO.setParentId(permission.getParentId());
            //判断是否包含
            boolean contains = permissionIdByRoleId.contains(permission.getId());
            if (contains) {
                permissionDTO.setChecked(true);
            } else {
                permissionDTO.setChecked(false);
            }
            //权限DTO添加到List中
            permissionDTOList.add(permissionDTO);
        }

        //构造菜单树
        //三层结构，从大到小来查
        for (PermissionDTO permissionDTO : permissionDTOList) {
            //分流，组成一颗树，返回的是树的结构
            // 寻找子节点
            for (PermissionDTO e : permissionDTOList) {
                if (e.getParentId() == permissionDTO.getId()) {
                    permissionDTO.getChildren().add(e);
                }
            }
            // 判断父节点，添加到集合
            if (permissionDTO.getParentId() == 0) {
                resultMenuList.add(permissionDTO);
            }
        }
        return resultMenuList;
    }

    @Override
    public List<PermissionDTO> getMenuList() {
        //可能有多个父节点为0的节点，构成一个List集合
        List<Permission> permissionList = permissionDao.getAllPermission();

        List<PermissionDTO> permissionDTOList = new ArrayList<>();

        //返回权限菜单列表
        List<PermissionDTO> resultMenuList = new ArrayList<>();

        //循环遍历所有权限信息
        for (Permission permission : permissionList) {
            PermissionDTO permissionDTO = new PermissionDTO();
            //权限id
            permissionDTO.setId(permission.getId());
            //权限名称
            permissionDTO.setPermissionName(permission.getPermissionName());
            //权限父节点
            permissionDTO.setParentId(permission.getParentId());
            //权限路径
            permissionDTO.setPath(permission.getPath());
            //权限组件
            permissionDTO.setComponent(permission.getComponent());
            //权限标识
            if (permission.getModuleId() != 0 || permission.getActionId() != 0) {
                String moduleCodeByModuleId = moduleService.getModuleCodeByModuleId(permission.getModuleId());
                String actionCodeByActionId = actionService.getActionCodeByActionId(permission.getActionId());
                permissionDTO.setPermissionCode(moduleCodeByModuleId.concat("_").concat(actionCodeByActionId));
            }
            //权限类型
            permissionDTO.setPermissionType(permission.getPermissionType());
            //创建时间
            permissionDTO.setCreateTime(permission.getCreatedTime());
            //权限DTO添加到List中
            permissionDTOList.add(permissionDTO);
        }

        //构造菜单树
        //三层结构，从大到小来查
        for (PermissionDTO permissionDTO : permissionDTOList) {
            //分流，组成一颗树，返回的是树的结构
            // 寻找子节点
            for (PermissionDTO e : permissionDTOList) {
                if (e.getParentId() == permissionDTO.getId()) {
                    permissionDTO.getChildren().add(e);
                }
            }
            // 判断父节点，添加到集合
            if (permissionDTO.getParentId() == 0) {
                resultMenuList.add(permissionDTO);
            }
        }
        return resultMenuList;
    }

    @Override
    public Boolean createNextFloor(MenuCreateReq req) {
        //permissionId作为新增下一级的父节点
        Permission permission = new Permission();
        permission.setPermissionName(req.getPermissionName());
        permission.setPermissionType(req.getType());
        permission.setPath(req.getPath());
        permission.setComponent(req.getComponent());
        permission.setParentId(req.getPermissionParentId());
        //判断如果是新建同级菜单，比如一级
        if (req.getWhichFloor() == 1) {
            permission.setActionId(0);
            permission.setModuleId(0);
        } else {
            String permissionCode = req.getPermissionCode();
            //communist_manage_select，以第二个下划线为分割module_name_action_name
            String actionCode = permissionCode.substring(permissionCode.indexOf("_", permissionCode.indexOf("_") + 1) + 1);
            String moduleCode = permissionCode.substring(0, permissionCode.indexOf("_", permissionCode.indexOf("_") + 1));
            Module module = moduleService.getModuleByModuleName(moduleCode);
            permission.setModuleId(module.getId());
            Action action = actionService.getActionByActionName(actionCode);
            permission.setActionId(action.getId());
        }

        Boolean flag = permissionDao.creatNextFloor(permission);
        return flag;
    }

    @Override
    public Boolean updateMenuMessage(MenuUpdateMessageReq req) {
        Permission permission = new Permission();
        //权限名称permissionName，权限路径path，权限标识permissionCode，权限Id permissionId
        permission.setId(req.getPermissionId());
        permission.setPermissionName(req.getPermissionName());
        permission.setPath(req.getPath());
        //处理permission_code问题
        Integer whichFloor = req.getWhichFloor();
        if (whichFloor == 1) {
            permission.setActionId(0);
            permission.setModuleId(0);
        } else {
            String permissionCode = req.getPermissionCode();
            //communist_manage_select，以第二个下划线为分割module_name_action_name
            String actionCode = permissionCode.substring(permissionCode.indexOf("_", permissionCode.indexOf("_") + 1) + 1);
            String moduleCode = permissionCode.substring(0, permissionCode.indexOf("_", permissionCode.indexOf("_") + 1));
            Module module = moduleService.getModuleByModuleName(moduleCode);
            permission.setModuleId(module.getId());
            Action action = actionService.getActionByActionName(actionCode);
            permission.setActionId(action.getId());
        }
        Boolean flag = permissionDao.updateMenuMessage(permission);
        return flag;
    }

    @Override
    public Boolean deleteMenuMessage(MenuDeleteMenuMessageReq req) {
        //连孩子都要删除
        List<Permission> permissionByParentId = permissionDao.getPermissionByParentId(req.getPermissionId());
        Set<Integer> deleteSet =new HashSet<>();
        //首先判断是否是最后一级，就是第三级，第三级没有孩子节点了
        if (permissionByParentId ==null){
            return permissionDao.deleteMenuMessage(req.getPermissionId());
        }else {
            deleteSet.add(req.getPermissionId());
            for (Permission permission : permissionByParentId) {
                List<Permission> permissionListByFirstOrSecondGeneration = permissionDao.getPermissionByParentId(permission.getId());
                //判断是第一代还是第二代，如果是空req.getPermissionId()就是第二代，如果不是空req.getPermissionId()就是第一代
                if (permissionListByFirstOrSecondGeneration.size() != 0) {
                    for (Permission permissionForFirstGeneration:permissionListByFirstOrSecondGeneration) {
                        //如果存在第一代，则把permissionListByFirstOrSecondGeneration中的id加入到deleteList中,也就是说permissionListByFirstOrSecondGeneration
                        //是第三代，req.getPermissionId()是第一级
                        deleteSet.add(permissionForFirstGeneration.getId());
                    }
                    deleteSet.add(permission.getId());
                }else{
                    //否则req.getPermissionId()是第二级,只有下级的孩子节点
                    deleteSet.add(permission.getId());
                }
            }
            //hashSet转List
            List<Integer> deleteList = new ArrayList<>(deleteSet);
            int sum = 0;
            for (Integer e : deleteList) {
                Boolean flagList = permissionDao.deleteMenuMessage(e);

                //删除之前要把role_permission跟role连接的数据都要删掉
                //删除当前节点的
                rolePermissionService.updateRolePermissionOut(e);

                if (flagList == true ){
                    sum++;
                }
            }
            if (sum == deleteList.size()) {
                return true;
            }else {
                return false;
            }

        }

    }

}
